/**
 * ==========================================================================
 * ILOVEFREE样式迁移JavaScript系统
 * 替换UIKit组件，实现现代化过滤系统
 * ==========================================================================
 */

class IlovefreeMigration {
    constructor() {
        this.selectedTags = {};
        this.categories = {};
        this.filterDelay = 300;
        this.init();
    }

    /**
     * 初始化迁移系统
     */
    init() {
        this.replaceUIKitComponents();
        this.initializeCategories();
        this.bindEvents();
        this.setupAnimations();
        console.log('🎨 Ilovefree迁移系统已初始化');
    }

    /**
     * 替换UIKit组件属性 - 适配已更新的HTML结构
     */
    replaceUIKitComponents() {
        console.log('🔧 开始替换UIKit组件...');

        // 处理现有的data-uk-filter属性（如果有）
        document.querySelectorAll('[data-uk-filter]').forEach(element => {
            const filters = element.getAttribute('data-uk-filter');
            element.setAttribute('data-tag-filters', filters);
            element.removeAttribute('data-uk-filter');
            console.log('✅ 转换data-uk-filter属性:', filters);
        });

        // 确保所有nav-grid正确设置
        document.querySelectorAll('.nav-grid, [data-uk-grid]').forEach(grid => {
            grid.removeAttribute('data-uk-grid');
            grid.classList.add('nav-grid');
            grid.style.removeProperty('position');
            grid.style.removeProperty('height');
            console.log('✅ 设置nav-grid:', grid.className);
        });

    
        // 绑定标签点击事件（如果未绑定）
        document.querySelectorAll('.tag-btn').forEach(btn => {
            if (!btn.hasAttribute('data-click-bound')) {
                const tagId = btn.getAttribute('data-tag-id');
                const tagFilter = btn.getAttribute('data-tag-filter');
                const categoryId = btn.closest('.tags-container')?.id;

                if (categoryId && tagId) {
                    btn.onclick = () => {
                        console.log('🏷️ 点击标签:', categoryId, tagId, tagFilter);
                        this.filterByTag(categoryId, parseInt(tagId));
                    };
                    btn.setAttribute('data-click-bound', 'true');
                    console.log('✅ 绑定标签点击事件:', categoryId, tagId);
                }
            }
        });

        // 确保分类标题正确设置
        document.querySelectorAll('.category-header').forEach(header => {
            if (!header.querySelector('.category-icon')) {
                const categoryTitle = header.querySelector('.category-title');
                if (categoryTitle && !categoryTitle.querySelector('.category-icon')) {
                    const icon = document.createElement('div');
                    icon.className = 'category-icon';
                    categoryTitle.insertBefore(icon, categoryTitle.firstChild);
                    console.log('✅ 添加分类图标');
                }
            }
        });

        console.log('✅ UIKit组件替换完成');
    }

    /**
     * 更新标签数量显示
     */
    updateTagCounts(categoryId) {
        const category = this.categories[categoryId];
        if (!category) return;

        const container = document.getElementById(categoryId);
        if (!container) return;

        const tagButtons = container.querySelectorAll('.tag-btn');

        tagButtons.forEach(btn => {
            const tagFilter = btn.getAttribute('data-tag-filter');
            const countElement = btn.querySelector('.tag-count');

            if (countElement && tagFilter) {
                if (tagFilter === '推荐') {
                    // "推荐"标签显示所有卡片数量
                    countElement.textContent = category.cards.length;
                } else {
                    // 其他标签显示匹配的卡片数量
                    const count = category.tagCounts[tagFilter] || 0;
                    countElement.textContent = count;
                }
                console.log(`🏷️ 更新标签数量: ${categoryId} - ${tagFilter}: ${countElement.textContent}`);
            }
        });
    }

    /**
     * 初始化分类数据 - 适配已更新的HTML结构
     */
    initializeCategories() {
        console.log('📂 初始化分类数据...');

        document.querySelectorAll('.tags-container').forEach(container => {
            const categoryId = container.id;

            if (!categoryId) {
                console.warn('⚠️ 找到没有ID的tags-container:', container);
                return;
            }

            const activeBtn = container.querySelector('.tag-btn.active');
            const selectedTag = activeBtn ? parseInt(activeBtn.getAttribute('data-tag-id')) : 0;

            this.categories[categoryId] = {
                id: categoryId,
                selectedTag: selectedTag,
                cards: [],
                tagCounts: {}
            };

            // 查找该分类下的nav-grid（可能在不同的DOM位置）
            let navGrid = container.nextElementSibling;
            while (navGrid && !navGrid.classList.contains('nav-grid')) {
                navGrid = navGrid.nextElementSibling;
            }

            if (!navGrid) {
                // 如果没找到相邻的，尝试在content-section中查找
                const section = container.closest('.content-section');
                navGrid = section?.querySelector('.nav-grid');
            }

            if (navGrid) {
                const cards = navGrid.querySelectorAll('.nav-link');
                console.log(`📊 分类 ${categoryId} 找到 ${cards.length} 个卡片`);

                cards.forEach(card => {
                    const filters = card.getAttribute('data-tag-filters') || '';
                    const tags = filters.split(',').map(tag => tag.trim()).filter(tag => tag);

                    this.categories[categoryId].cards.push({
                        element: card,
                        tags: tags
                    });

                    // 统计每个标签的数量
                    tags.forEach(tag => {
                        this.categories[categoryId].tagCounts[tag] = (this.categories[categoryId].tagCounts[tag] || 0) + 1;
                    });
                });

                // 计算并更新标签数量
                this.updateTagCounts(categoryId);
            } else {
                console.warn('⚠️ 分类', categoryId, '未找到对应的nav-grid');
            }

            this.selectedTags[categoryId] = selectedTag;
            console.log(`✅ 初始化分类 ${categoryId}: 选中标签${selectedTag}, 卡片${this.categories[categoryId].cards.length}个`);
        });

        console.log('📂 所有分类数据初始化完成:', this.categories);
    }

    /**
     * 绑定事件监听器
     */
    bindEvents() {
        // 标签点击事件已通过onclick绑定

        // 键盘导航支持
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Tab') {
                this.setupKeyboardNavigation();
            }
        });

        // 响应式布局监听
        window.addEventListener('resize', this.debounce(() => {
            this.handleResponsiveLayout();
        }, 250));

        // 搜索功能（如果存在）
        const searchInput = document.querySelector('#search-input');
        if (searchInput) {
            searchInput.addEventListener('input', this.debounce((e) => {
                this.handleSearch(e.target.value);
            }, 300));
        }
    }

    /**
     * 设置动画效果
     */
    setupAnimations() {
        // 为卡片添加渐进式动画
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.style.animationPlayState = 'running';
                }
            });
        }, { threshold: 0.1 });

        document.querySelectorAll('.nav-link').forEach(card => {
            card.style.animationPlayState = 'paused';
            observer.observe(card);
        });
    }

    /**
     * 按标签过滤
     */
    filterByTag(categoryId, tagId) {
        const category = this.categories[categoryId];
        if (!category) return;

        this.selectedTags[categoryId] = tagId;

        // 更新标签按钮状态
        this.updateTagButtons(categoryId, tagId);

        // 过滤卡片
        this.filterNavigationItems(categoryId, tagId);

        // 更新分类状态
        category.selectedTag = tagId;

        // 更新当前激活标签的可见数量
        this.updateActiveTagCount(categoryId, tagId);
    }

    /**
     * 更新标签按钮状态
     */
    updateTagButtons(categoryId, activeTagId) {
        const container = document.getElementById(categoryId);
        if (!container) return;

        container.querySelectorAll('.tag-btn').forEach(btn => {
            const btnTagId = parseInt(btn.getAttribute('data-tag-id'));
            if (btnTagId === activeTagId) {
                btn.classList.add('active');
            } else {
                btn.classList.remove('active');
            }
        });
    }

    /**
     * 更新当前激活标签的可见数量
     */
    updateActiveTagCount(categoryId, tagId) {
        const category = this.categories[categoryId];
        if (!category) return;

        const container = document.getElementById(categoryId);
        if (!container) return;

        const activeBtn = container.querySelector(`.tag-btn[data-tag-id="${tagId}"]`);
        const countElement = activeBtn?.querySelector('.tag-count');

        if (!countElement) return;

        let visibleCount = 0;

        if (tagId === 0) {
            // "推荐"标签显示所有可见卡片数量
            visibleCount = category.cards.filter(card => {
                return card.element.style.display !== 'none' && !card.element.classList.contains('hidden');
            }).length;
        } else {
            // 其他标签显示当前过滤后的可见数量
            const tagFilter = activeBtn?.getAttribute('data-tag-filter');
            if (tagFilter) {
                visibleCount = category.cards.filter(card => {
                    const isVisible = card.element.style.display !== 'none' && !card.element.classList.contains('hidden');
                    const matchesTag = card.tags.includes(tagFilter);
                    return isVisible && matchesTag;
                }).length;
            }
        }

        countElement.textContent = visibleCount;
        console.log(`🔢 更新激活标签数量: ${categoryId} - 标签${tagId}: ${visibleCount}`);
    }

    /**
     * 过滤导航卡片
     */
    filterNavigationItems(categoryId, tagId) {
        const category = this.categories[categoryId];
        if (!category) return;

        let visibleCount = 0;

        category.cards.forEach((card, index) => {
            const shouldShow = tagId === 0 || this.matchesTag(card.tags, tagId, categoryId);

            if (shouldShow) {
                this.showCard(card.element, index);
                visibleCount++;
            } else {
                this.hideCard(card.element);
            }
        });

        // 检查空状态
        this.checkEmptyState(categoryId, visibleCount);

        // 记录过滤操作
        this.logFilterAction(categoryId, tagId, visibleCount);
    }

    /**
     * 检查卡片是否匹配标签
     */
    matchesTag(cardTags, tagId, categoryId) {
        const container = document.getElementById(categoryId);
        const activeBtn = container?.querySelector(`.tag-btn[data-tag-id="${tagId}"]`);
        const filterText = activeBtn?.getAttribute('data-tag-filter');

        return filterText && cardTags.includes(filterText);
    }

    /**
     * 显示卡片
     */
    showCard(element, index) {
        element.style.display = 'block';
        element.classList.remove('hidden', 'filtering');
        element.classList.add('visible');

        // 添加渐进式动画
        setTimeout(() => {
            element.style.opacity = '1';
            element.style.transform = 'scale(1)';
        }, index * 50);
    }

    /**
     * 隐藏卡片
     */
    hideCard(element) {
        element.classList.remove('visible');
        element.classList.add('filtering');

        setTimeout(() => {
            element.style.opacity = '0';
            element.style.transform = 'scale(0.8)';
            element.classList.add('hidden');
            element.classList.remove('filtering');

            setTimeout(() => {
                element.style.display = 'none';
            }, 300);
        }, 50);
    }

    /**
     * 检查空状态
     */
    checkEmptyState(categoryId, visibleCount) {
        const category = this.categories[categoryId];
        const gridElement = document.getElementById(categoryId)?.nextElementSibling;

        if (!gridElement) return;

        // 移除现有空状态提示
        const existingEmpty = gridElement.querySelector('.empty-state');
        if (existingEmpty) {
            existingEmpty.remove();
        }

        // 如果没有可见卡片，显示空状态
        if (visibleCount === 0) {
            const emptyState = document.createElement('div');
            emptyState.className = 'empty-state';
            emptyState.innerHTML = `
                <div style="text-align: center; padding: 3rem; color: var(--text-muted);">
                    <i class="fas fa-search" style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.5;"></i>
                    <p>没有找到匹配的资源</p>
                    <p style="font-size: 0.875rem; margin-top: 0.5rem;">试试选择其他标签</p>
                </div>
            `;
            gridElement.appendChild(emptyState);
        }
    }

    /**
     * 处理搜索功能
     */
    handleSearch(searchTerm) {
        if (!searchTerm.trim()) {
            // 如果搜索为空，恢复当前标签过滤
            Object.keys(this.selectedTags).forEach(categoryId => {
                this.filterNavigationItems(categoryId, this.selectedTags[categoryId]);
            });
            return;
        }

        const term = searchTerm.toLowerCase();

        Object.keys(this.categories).forEach(categoryId => {
            const category = this.categories[categoryId];
            let visibleCount = 0;

            category.cards.forEach(card => {
                const title = card.element.querySelector('h4')?.textContent.toLowerCase() || '';
                const description = card.element.querySelector('p')?.textContent.toLowerCase() || '';

                const matchesSearch = title.includes(term) || description.includes(term);
                const matchesTag = this.selectedTags[categoryId] === 1 ||
                    this.matchesTag(card.tags, this.selectedTags[categoryId], categoryId);

                if (matchesSearch && matchesTag) {
                    this.showCard(card.element, visibleCount);
                    visibleCount++;
                } else {
                    this.hideCard(card.element);
                }
            });

            this.checkEmptyState(categoryId, visibleCount);
        });
    }

    /**
     * 设置键盘导航
     */
    setupKeyboardNavigation() {
        // 为标签按钮添加键盘导航
        document.querySelectorAll('.tag-btn').forEach(btn => {
            btn.setAttribute('tabindex', '0');
            btn.setAttribute('role', 'button');
            btn.setAttribute('aria-pressed', btn.classList.contains('active'));
        });
    }

    /**
     * 处理响应式布局
     */
    handleResponsiveLayout() {
        const width = window.innerWidth;

        // 根据屏幕宽度调整网格布局
        document.querySelectorAll('.nav-grid').forEach(grid => {
            if (width < 480) {
                grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(140px, 1fr))';
            } else if (width < 768) {
                grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(150px, 1fr))';
            } else if (width < 1024) {
                grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(160px, 1fr))';
            } else {
                grid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(180px, 1fr))';
            }
        });
    }

    /**
     * 记录过滤操作
     */
    logFilterAction(categoryId, tagId, visibleCount) {
        if (typeof gtag !== 'undefined') {
            gtag('event', 'filter', {
                'category': categoryId,
                'tag_id': tagId,
                'visible_count': visibleCount
            });
        }

        console.log(`🔍 过滤操作: ${categoryId} -> 标签${tagId}, 显示${visibleCount}个结果`);
    }

    /**
     * 防抖函数
     */
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    /**
     * 获取当前过滤状态
     */
    getFilterState() {
        return { ...this.selectedTags };
    }

    /**
     * 重置所有过滤
     */
    resetFilters() {
        Object.keys(this.selectedTags).forEach(categoryId => {
            this.filterByTag(categoryId, 1);
        });
    }

    /**
     * 导出配置
     */
    exportConfig() {
        return {
            categories: this.categories,
            selectedTags: this.selectedTags,
            timestamp: new Date().toISOString()
        };
    }

    /**
     * 导入配置
     */
    importConfig(config) {
        if (config.categories && config.selectedTags) {
            this.categories = config.categories;
            this.selectedTags = config.selectedTags;

            // 更新UI状态
            Object.keys(this.selectedTags).forEach(categoryId => {
                this.updateTagButtons(categoryId, this.selectedTags[categoryId]);
                this.filterNavigationItems(categoryId, this.selectedTags[categoryId]);
            });
        }
    }
}

/**
 * 初始化迁移系统
 */
document.addEventListener('DOMContentLoaded', () => {
    // 检查是否已经加载了UIKit
    if (typeof UIkit !== 'undefined') {
        console.warn('⚠️ 检测到UIKit框架，可能会导致样式冲突');
    }

    // 初始化迁移系统
    window.ilovefreeMigration = new IlovefreeMigration();

    // 添加全局方法供外部调用
    window.filterByTag = (categoryId, tagId) => {
        window.ilovefreeMigration.filterByTag(categoryId, tagId);
    };

    // 开发者工具（仅在开发环境）
    if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
        window.ILOVEFREE_DEV = {
            migration: window.ilovefreeMigration,
            reset: () => window.ilovefreeMigration.resetFilters(),
            export: () => window.ilovefreeMigration.exportConfig(),
            import: (config) => window.ilovefreeMigration.importConfig(config)
        };

        console.log('🛠️ 开发者工具已加载，使用 ILOVEFREE_DEV 访问');
    }
});

// 导出模块（如果使用模块系统）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = IlovefreeMigration;
}